import Worker from './timer.worker.js'

export default class TimerWorker {
  worker;
  timers;
  constructor() {
    this.start()
  }
  startTimer(id, interval, fun) {
    if (this.worker && !this.timers[id]) {
      this.timers[id] = fun
      this.worker.postMessage({ action: 'startTimer', id, interval })
    }
    return this
  }
  stopTimer(id) {
    if (this.worker && this.timers[id]) {
      this.worker.postMessage({ action: 'stopTimer', id })
      delete this.timers[id]
    }
    return this
  }
  stopAllTimers() {
    if (this.worker) {
      this.worker.postMessage({ action: 'stopAllTimers' })
      this.timers = {}
    }
    return this
  }
  start() {
    if (!this.worker) {
      const worker = new Worker()
      worker.onmessage = (event) => {
        this.timers[event.data.id]()
      }
      this.worker = worker
      this.timers = {}
    }
    return this
  }
  terminate() {
    if (this.worker) {
      this.stopAllTimers()
      this.worker.terminate()
      this.worker = undefined
      this.timers = undefined
    }
    return this
  }
}

